package sparkStream

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, ProducerRecord}
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.{Seconds, StreamingContext}

import java.util

/**
 * @Time ： 2024/10/29
 * */
object HelloSparkStream {

  def main(args: Array[String]): Unit = {

    // 创建 sparkConf 配置项
    val conf = new SparkConf().setMaster("local[*]").setAppName("helloStream")
    val ssc = new StreamingContext(conf, Seconds(2))
    ssc.sparkContext.setLogLevel("error")

    // kafka 配置
    val kfkParams = Map[String, Object](
      "bootstrap.servers" -> "cheng:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "niit",
      "enable.auto.commit" -> (false: java.lang.Boolean)
    )

    // 定义 kafka 主题
    val topicName = Array("stuInfo")

    // 创建 Kafka 数据流
    val streamRdd = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topicName, kfkParams)
    )

    // producer 配置
    val property = new util.HashMap[String, Object]()
    property.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.65.128:9092")
    property.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")
    property.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")
    // 使用时间窗口对单词进行统计
    val line = streamRdd.map(_.value())
    val res = line.flatMap(_.split("\t"))
      .map((_, 1))
      .reduceByKeyAndWindow(_ + _, Seconds(4), Seconds(4))

    res.foreachRDD(
      x => {
        println("-------------数据 结果------------")
        x.foreach(println)
        x.foreach(
          obj => {
            val kfkProducer = new KafkaProducer[String, String](property)
            kfkProducer.send(new ProducerRecord[String, String]("16test1", obj.toString()))
            kfkProducer.close()
          }

        )
      }
    )



    //    // 使用 producer 发送统计结果
    //    streamRdd.foreachRDD(
    //      x => {
    //        if (!x.isEmpty()) {
    //          val line = x.map(_.value())
    //          val result = line.flatMap(_.split("\t")).map((_, 1)).reduceByKey(_ + _)
    //          result.foreach(println)
    //
    //          result.foreach(
    //            obj => {
    //              val kfkProducer = new KafkaProducer[String, String](property)
    //              kfkProducer.send(new ProducerRecord[String, String]("16test2", obj.toString()))
    //              kfkProducer.close()
    //            }
    //          )
    //        }
    //      }
    //    )

    ssc.start()
    ssc.awaitTermination()
  }
}


